//
//  NLHomeController.swift
//  sinaWeibo7110
//
//  Created by 安静清晨 on 2017/1/4.
//  Copyright © 2017年 walk-in-minds. All rights reserved.
//

import UIKit
import SVProgressHUD

let homeCellID = "homeCellID"
let homeTweetedCellID = "homeTweetedCellID"

class NLHomeController: NLBaseTableViewController {
    
//home_timeline https://api.weibo.com/2/statuses/home_timeline.json
    
    lazy var homeViewModel = NLHomeViewModel()
    //记录
    var refreshView = NLRefreshview()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //访客视图设置, 右上角扫面按钮设置
        //判断用户是否登录
        if !userLogin {
            //没有登录
            //设置访客视图的信息
            
            visitorView.updateUI(IconName: "visitordiscover_feed_image_smallicon", lbl_text: "注册了关注一些人回来看看有什么毛线惊喜", isHome: true)
            return
        }
        
        
        
        
        //右上按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", imageName: "navigationbar_pop", target: self, action: #selector(didClickToScan))
        
        
        //通过homeViewModel, 网络请求hometimeline数据
        loadHomeTimeLineData()
        
        
        //注册
        tableView.register(UINib.init(nibName: "NLHomeCell", bundle: nil), forCellReuseIdentifier: homeCellID)
        tableView.register(UINib.init(nibName: "NLHomeTweetedCell", bundle: nil), forCellReuseIdentifier: homeTweetedCellID)
        
 
        //分割线去掉
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.clear
        
        //设置背景
        let img = UIImage(named: "111")
        let imgFlower = UIImageView(image: img)
        let flowerView = UIView()
        flowerView.addSubview(imgFlower)
        tableView.backgroundView = flowerView
        
        //设置tableView的tableFootter
        tableView.tableFooterView = upPullIndicator
        //自定义下拉刷新视图

        view.addSubview(refreshView)
        //监听用户下拉刷新的操作
        refreshView.addTarget(self, action: #selector(loadHomeTimeLineData), for: .valueChanged)
        
        //监听用户下拉刷新的操作
//        refreshControl?.addTarget(self, action: #selector(loadHomeTimeLineData), for: .valueChanged)
        
    }
    
    //上拉指示器
    lazy var upPullIndicator : UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        return indicator
        
    }()
    
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 前者判断是为了防止重复请求
        if upPullIndicator.isAnimating == false && indexPath.row == self.homeViewModel.homeCellArr.count - 2 {
            
            upPullIndicator.startAnimating()
            
            self.refreshControl?.endRefreshing()
            loadHomeTimeLineData()
//            tableView.reloadData()
        }
        
        
        
        
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.homeViewModel.homeCellArr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.homeViewModel.homeCellArr[indexPath.row]
        var identifier : String?
        //判断model中是否含有
        if (model.statuses?.retweeted_status != nil) {
            //是转发微博
            identifier = homeTweetedCellID
        }else{
            
            identifier = homeCellID
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier!) as! NLHomeCell
        
        cell.homeCellViewModel = model
        
        cell.selectionStyle = .none
        cell.backgroundColor = UIColor.clear
        return cell
    }
    

    
    //设置cell行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //思路: 返回toolbar的MaxY  即cell的高度
        //实例化一个不显示的cell对象,专门用来计算行高
        //不能直接通过[ dequequ得到cell-cell中得到toolbar ]的方式, 因为一调用dequeque就会去调用行高, 这样形成递归.
        //通过indexpath-model-cellid-xib-toolbar
        let viewModel = self.homeViewModel.homeCellArr[indexPath.item]
        
        let cellID = viewModel.statuses?.retweeted_status != nil ? "NLHomeTweetedCell" : "NLHomeCell"
        let cell = UINib(nibName: cellID, bundle: nil).instantiate(withOwner: nil, options: nil).last as! NLHomeCell
        
        cell.homeCellViewModel = viewModel
        //因为不显示, 没有frame. 需要强制layout一下.
        cell.layoutIfNeeded()
        
        //print(cell.toolBar.frame.maxY)
        
        return cell.toolBar.frame.maxY
        
 }
    //wuuwuwu
//        if viewModel.statuses?.retweeted_status != nil {
//            //转发微博
//            
//            let tweetedCell = UINib(nibName: "NLHomeTweetedCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! NLHomeCell
//            
//            return tweetedCell.toolBar.frame.maxY
//            
//        }else{
//            let originalCell = UINib(nibName: "NLHomeCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! NLHomeCell
//            
//            return originalCell.toolBar.frame.maxY
//            
//            
//        }
        
    
    
    
    
    
    
    

    
    func loadHomeTimeLineData(){
        
        
        self.homeViewModel.getHomeTimeLineData(isPullUp: upPullIndicator.isAnimating) { (success) in
            if !success{
                
                SVProgressHUD.showError(withStatus: "妈个鸡没网啦!!!")
                return
            }else{
                self.upPullIndicator.stopAnimating()
                self.tableView.reloadData()
                self.refreshControl?.endRefreshing()
                self.refreshView.backToNormal()
                
                
                
            }
        }
        
        
        

     
    }
    
    

 
    
    func didClickToScan(){
        
        let scanVC = NLScanViewController()
        self.navigationController?.pushViewController(scanVC, animated: true)
        _ = self.popoverPresentationController
    }

}
